/*
 * @Description: 选择档案位置
 * @Author: Rfan
 * @Date: 2022-07-13 19:10:27
 * @LastEditTime: 2022-07-13 19:10:47
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Form, Modal, Radio, Select } from 'antd';
import { fetchArchivesLevelWithPage } from '@/api/archives/archives';
import { useBoxMgtContext } from '../../contexts/BoxMgtContext';
import FieldMap from '@/components/LevelTable/componentes/dialogs/FieldMap';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';

const { Option } = Select;

interface IReplaceRecordDialogProps extends ICommonDialog {
  type?: 'filing' | 'transfer';
  selectItems: number[];
}

const ReplaceRecordDialog: FC<IReplaceRecordDialogProps> = (props) => {
  const { visible, type, selectItems, onClose } = props;
  const { selectAT } = useBoxMgtContext();
  const [form] = Form.useForm();

  // 字段映射弹窗
  const [mapVisible, setMapVisible] = useState(false);
  // 案卷列表
  const [fileList, setFileList] = useState([]);

  const [listQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {
      atCode: selectAT.atCode,
      atType: selectAT.atType,
      commonParams: {
        dbName: 'data'
      },
      level: 2
    }
  });

  useEffect(() => {
    if (visible) {
      if (type === 'transfer' && selectAT.atLevel >= 2) {
        fetchArchivesLevelWithPage(listQuery).then((res) => {
          const _data = res.data;
          if (_data.results) {
            setFileList(_data.results.data);
          }
        });
      }
    }
  }, [visible]);

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 新增档案类型
  const onFinish = (vals: any) => {
    //  finish methods
    const { atCode, atType, atLevel } = selectAT;
    const params = Object.assign(vals, {
      coordinate: {
        atCode,
        atType,
        level: atLevel
      },
      movingEntryInfo: {
        entryIdList: selectItems
      }
    });
    onClose(params);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="选择归档位置"
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          确认
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        preserve={false}
        initialValues={{ toDb: 'data' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          name="toDb"
          label="归档位置"
          extra="字典库显示名称，不能重复"
          rules={[{ required: true }]}
        >
          <Radio.Group>
            <Radio value="data">导入整编库</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="档案类型">
          <Select defaultValue={selectAT.id} disabled>
            <Option value={selectAT.id}>{selectAT.atName}</Option>
          </Select>
        </Form.Item>
        {type === 'transfer' && (
          <Form.Item name="entryId" label="选择案卷">
            <Select>
              {fileList.map((file) => (
                <Option value={file.id}>{file.title}</Option>
              ))}
            </Select>
          </Form.Item>
        )}
        <Form.Item label="字段映射">
          <Button
            type="link"
            disabled
            onClick={() => {
              setMapVisible(true);
            }}
          >
            设定字段映射
          </Button>
        </Form.Item>
      </Form>
      {useMemo(
        () => (
          <FieldMap visible={mapVisible} onClose={() => setMapVisible(false)} />
        ),
        [mapVisible]
      )}
    </Modal>
  );
};
export default ReplaceRecordDialog;
